import tool from "@/utils/tool.js";

let BASE_URL = 'http://localhost:8080';
let excludeFilterUrls = ['/user/login', '/user/register'];

function http(param) {
    let url = param.url;
    let method = param.method;
    let header = {
      ...param.header
    };
    let data = {
      ...param.data
    };
    let showLoading = param.showLoading || false;

    // 判断是否登录
    let token = tool.data.get('TOKEN');
    if (token) {
        header['Token'] = token;
    } else if (!excludeFilterUrls.includes(url)) {
        uni.navigateTo({
            url: '/pages/user/children/signin/signin'
        });
    }

    // 过滤属性为null的
    if (data) {
        for (var key in data) {
            if (data[key] === null || data[key] === undefined || data[key] === "null") {
                delete data[key];
            }
        }
    }

    if (method) {
        header = {
           ...header,
            'content-type': "application/json"
        };
    }

    if (showLoading) {
        uni.showLoading();
    }

    return new Promise((resolve, reject) => {
        uni.request({
            url: BASE_URL + url,
            data: data,
            method: method,
            header: header,
            timeout: 5000, // 设置超时时间为5秒，可根据实际情况调整
            success: (res) => {
                if (showLoading) {
                    uni.hideLoading();
                }
                if (res.data.code === 1) {
                    resolve(res.data);
                } else {
                    uni.showToast({
                        title: res.data.msg || '请求成功但业务逻辑返回错误',
                        icon: 'none'
                    });
                    reject(new Error(res.data.msg || '请求成功但业务逻辑返回错误'));
                }
            },
            fail: (err) => {
                if (showLoading) {
                    uni.hideLoading();
                }
                uni.showToast({
                    title: err.errMsg || '请求失败，请检查网络或稍后重试',
                    icon: 'none'
                });
                reject(err);
            }
        });
    });
}

export default http;